package com.gitee.tianchaohongyu.jdcl.aspect;

import com.gitee.tianchaohongyu.jdcl.core.CleanReturns;
import com.gitee.tianchaohongyu.jdcl.core.CleanService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import javax.annotation.Resource;
import java.lang.reflect.Method;

/**
 * 对注解 @CleanReturns 的对象进行返回值清洗的切面
 */
@Aspect
public class CleanReturnsAspect {

  @Resource
  private CleanService cleanService;

  @Around("@within(cleanReturns) || @annotation(cleanReturns)")
  public Object around(ProceedingJoinPoint proceedingJoinPoint, CleanReturns cleanReturns) throws Throwable {
    Signature signature = proceedingJoinPoint.getSignature();
    Object ret = proceedingJoinPoint.proceed();
    if (ret != null && signature instanceof MethodSignature) {
      Method method = ((MethodSignature) signature).getMethod();
      String name = String.format("%s.%s", signature.getDeclaringType().getSimpleName(), signature.getName());
      boolean isCleanReturns = method.getDeclaredAnnotation(CleanReturns.class) != null || method.getDeclaringClass().getDeclaredAnnotation(CleanReturns.class) != null;
      if (ret != null && isCleanReturns) cleanService.cleanFields(name + "()返回值", ret);
    }
    return ret;
  }
}